package com.zd.commodity.userMng.dao.impl;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import utils.MD5Util;

import com.zd.commodity.dao.impl.BaseDao;
import com.zd.commodity.userMng.dao.IUserDao;
import com.zd.commodity.userMng.entity.Role;
import com.zd.commodity.userMng.entity.User;

public class UserDao extends BaseDao<User> implements IUserDao{

	@Override
	public User findByUsernameAndPwd(String username, String password) {
		List<User> list = getHibernateTemplate().find("from User where username=? and password=?",
				username,password);
		if(list.size()>0){
			return list.get(0);
		}else{
			return null;
		}
	}
	
	public User findByUsername(String username){
		List<User> list=getHibernateTemplate().find("from User where username='"+username+"'");
		if(list.size()>0){
			return list.get(0);
		}else{
			return null;
		}
	}

	@Override
	public DetachedCriteria getDetachedCriteria(User t1, User t2, Object param) {
		DetachedCriteria dc=DetachedCriteria.forClass(User.class);
		
		if(t1!=null){
			if(!"".equals(t1.getUsername())){
				dc.add(Restrictions.like("username", t1.getUsername(),MatchMode.ANYWHERE));
			}
			
			if(t1.getRole()!=null){
				if(!t1.getRole().getRolename().equals("") && t1.getRole().getRolename()!=null){
					dc=dc.createAlias("role", "r");
					dc.add(Restrictions.like("r.rolename", t1.getRole().getRolename(), MatchMode.ANYWHERE));
				}
			}
		}
		dc.addOrder(Order.desc("addtime"));
		return dc;
	}
	
	@Override
	public void add(User t) {		
		String md5Pswd = MD5Util.MD5(t.getUsername()+t.getPassword());
		
		//String loginIp = ServletActionContext.getRequest().getRemoteAddr();
		//第一次的登录时间和添加时间是一样的
		Timestamp logindate=new Timestamp(System.currentTimeMillis());
		
		t.setPassword(md5Pswd);
		t.setAddtime(logindate);
		//t.setLogindate(logindate);
		//t.setLoginip(loginIp);
		t.setStatus(String.valueOf(0));
		
		
		getHibernateTemplate().save(t);		
	}

}
